package com.example.app.service;

import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

// src/main/java/com/yourproject/websocket/WebSocketService.java
@Service
@RequiredArgsConstructor // Lombok，或手动 @Autowired
public class WebSocketService {

    private final SimpMessagingTemplate messagingTemplate;

    /**
     * 向指定用户发送点对点消息
     *
     * @param userId 用户ID
     * @param type   消息类型，如 "new_message", "conversation_updated"
     * @param payload 消息内容（Map、Object 等）
     */
    public void sendMessageToUser(Long userId, String type, Object payload) {
        messagingTemplate.convertAndSendToUser(
                userId.toString(),           // 用户ID（字符串）
                "/queue/messages",           // 目标队列
                Map.of("type", type, "data", payload) // 消息体
        );
    }

    /**
     * 快捷方法：发送新消息通知
     */
    public void notifyNewMessage(Long receiverId, Object messageData) {
        sendMessageToUser(receiverId, "new_message", messageData);
    }

    /**
     * 发送会话更新通知
     */
    public void notifyConversationUpdated(Long receiverId, Object conversationUpdate) {
        sendMessageToUser(receiverId, "conversation_updated", conversationUpdate);
    }

    /**
     * 广播消息（可选：用于群聊）
     */
    public void broadcastMessage(String topic, Object payload) {
        messagingTemplate.convertAndSend(topic, payload);
    }
}
